/**
 * YESBRAIN Javascript Library;
 * @author gongji
 */

/*
 * JSQL Client To Query/Operate local database like Sqlite in Chrome , etc .
 * Can use full-function sql provided by sqlite
 * sql differences from server to server 
 * but most of the basics are the same; 
 * 
 */

YESBRAIN.namespace("JSQL.Client");

YESBRAIN.JSQL.Client = {
		
		ClientDataBase : '',
		
		ClientDBVersion : '',
		
		ClientDBDesc : '',
		
		ClientDBSize : 0,
		
		DB : null,
		
		
		executeSQL : function(sql) {
			
			var clientdatabase = this.ClientDataBase ? this.ClientDataBase : _CLIENTDATABASE_;
			var clientdbversion = this.ClientDBVersion ? this.ClientDBVersion : _CLIENTDBVERSION_;
			var clientdbdesc = this.ClientDBDesc ? this.ClientDBDesc : _CLIENTDBDESC_;
			var clientdbsize = this.ClientDBSize ? this.ClientDBSize : _CLIENTDBSIZE_;
			
			var re = new RegExp(/\s*(select|insert|update|delete|create\s+table|drop\s+table)/ig);
			var res;
			var cmd;
			res = re.exec(sql);
			
			if(res) {
				cmd = res[1];
				cmd = cmd.toLowerCase().replace(" ","");
			} else {
				alert("command not supported yet!");
				return null;
			};
			
			var callbackdata;
			var success = function(tx, result) {
				if(cmd=="select") {
					var records = [];
					for(var i=0;i<result.rows.length;i++) {
						var record = result.rows.item(i);
						records.push(record);
					};
					callbackdata = records;
					alert(callbackdata);
				} else if(cmd=="insert") {
					callbackdata = true;
				} else if(cmd=="update") {
					callbackdata = result.rowsAffected;
				} 
				else if(cmd=="delete") {
					callbackdata = result.rowsAffected;
				}
				else if(cmd=="createtable") {
					callbackdata = true;
				}
				else if(cmd=="droptable") {
					callbackdata = true;
				};
			};
			
			var failure = function(tx, error) {
				alert(error.message);
				if(cmd=="select") {
					callbackdata = [];
				} else if(cmd=="insert") {
					callbackdata = false;
				} else if(cmd=="update") {
					callbackdata = -1;
				} 
				else if(cmd=="delete") {
					callbackdata = -1;
				}
				else if(cmd=="createtable") {
					callbackdata = false;
				}
				else if(cmd=="droptable") {
					callbackdata = false;
				};
			};
			if(!this.DB) {
				this.DB = openDatabase(clientdatabase,clientdbversion,clientdbdesc,clientdbsize);
			};
			
			if(this.DB) {
				this.DB.transaction(function(tx) {
						tx.executeSql(sql,[],success,failure);
					}
				);
			}
			else
			{
				alert("failed to connect to local database!");
			};

			while(callbackdata == null) {

			};
			return callbackdata;
		},
		
		querySQL : function(sql){
			return this.executeSQL(sql);
		}
};